package com.xdf.wxbebarrel.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdf.wxbebarrel.model.WechatMenuButton;
import com.xdf.wxbebarrel.model.WechatSubButton;
import com.xdf.wxbebarrel.model.WechatViewButton;
import com.xdf.wxbebarrel.model.WxAccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;

@Component
public class CreatMenu {
    @Autowired
    private WxAccessToken wxAccessToken;
    private static final ObjectMapper mapper = new ObjectMapper();

    public void create() throws IOException {
        WechatMenuButton button = new WechatMenuButton();
        // 顺杰货运 - 公司简介
        String companyProfile = SysConst.FRONT_END_URL + "/0101.html";
        String companyProfileEncoded = URLEncoder.encode(companyProfile);
        String companyProfileFull = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + DevMaterial.JZY.APPID + "&redirect_uri=" + companyProfileEncoded + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";


        // shunjie - company profile
        String companyProfileEn = SysConst.FRONT_END_URL + "/0201.html";
        String companyProfileEnEncoded = URLEncoder.encode(companyProfileEn);
        String companyProfileEnFull = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + DevMaterial.JZY.APPID + "&redirect_uri=" + companyProfileEnEncoded + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

        // 关于
        String adminUrl = URLEncoder.encode(SysConst.FRONT_END_URL + "/admin.html");
        String adminEncodedFull = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+DevMaterial.JZY.APPID
                +"&redirect_uri="+adminUrl+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

        // 主菜单第一个按钮 - 没有子菜单
        WechatSubButton sb01 = new WechatSubButton("企业云");
        sb01.getSub_button().add(new WechatViewButton("备用01", companyProfileFull));
        button.getButton().add(sb01);

        // 主菜单第二个按钮
        WechatSubButton sb02 = new WechatSubButton("客户云");
        sb02.getSub_button().add(new WechatViewButton("备用01", companyProfileEnFull));
        button.getButton().add(sb02);

        // 主菜单第三个按钮
        WechatSubButton sb03 = new WechatSubButton("关于");
        sb03.getSub_button().add(new WechatViewButton("管理员", adminEncodedFull));
        button.getButton().add(sb03);

        String btnString = mapper.writeValueAsString(button);

        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        String access_token = wxAccessToken.getAccessToken();
        url = url.replace("ACCESS_TOKEN", access_token);
        String result = HttpUtils.postForm(url, btnString,false);
        System.out.println("创建菜单的结果：" + result);
    }

}
